package com.huluobo.a2110mvpimdemo.mine;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.huluobo.a2110mvpimdemo.R;
import com.huluobo.a2110mvpimdemo.base.BaseFragment;
import com.huluobo.a2110mvpimdemo.login.LoginActivity;
import com.hyphenate.chat.EMClient;
import com.uuzuche.lib_zxing.activity.CodeUtils;

public class MineFragment extends BaseFragment<MineContract.View, MinePresenter> implements MineContract.View {

    private Button logoutBtn;
    private ImageView QRCode;

    @Override
    protected int bindLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initData() {
        presenter = new MinePresenter();
    }

    @Override
    protected void initView() {
        logoutBtn = findViewById(R.id.mine_btn_logout);
        logoutBtn.setOnClickListener(v -> {
            presenter.logout();
        });

        //getString(R.string.logoutString) 拿到string这个xml文件中对应id的String,当前这里拿到的就是:退出(%s)登录
        //EMClient.getInstance().getCurrentUser() 拿到的就是当前登录的用户名
        //String.format会找到第一个参数中带%s的位置,将第二个参数替换到对应的位置
        String username = String.format(getString(R.string.logoutString), EMClient.getInstance().getCurrentUser());
//        String usernameString = EMClient.getInstance().getCurrentUser();
//        logoutBtn.setText("退出(" + usernameString + ")退出");
        logoutBtn.setText(username);

        QRCode = findViewById(R.id.mine_QRCode);
        String QRCodeName = EMClient.getInstance().getCurrentUser();

        Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.img);
        Bitmap image = CodeUtils.createImage(QRCodeName, 400, 400, logo);
        QRCode.setImageBitmap(image);


    }

    @Override
    public void onLogoutSuccess() {
        dismissProgressDialog();
        getActivity().runOnUiThread(() -> {
            Toast.makeText(getActivity(), "退出登录成功", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            getActivity().finish();
        });
    }

    @Override
    public void onLogoutFailed(String error) {
        dismissProgressDialog();
        getActivity().runOnUiThread(() -> {
            Toast.makeText(getActivity(), "退出登录失败" + error, Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public void onStartLogout() {
        showProgressDialog("正在退出...");
    }
}